package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_LIST_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IShopTypeService shopTypeService;

    @Override
    public Result queryTypeList() {

       //List<ShopType> typeList = typeService
//                .query().orderByAsc("sort").list();
//        return Result.ok(typeList);

        //1、从redis查询店铺缓存
        String shoplist = stringRedisTemplate.opsForValue().get(CACHE_SHOP_LIST_KEY);

        //2、判断是否存在
        if (StrUtil.isNotBlank(shoplist)) {
            log.debug("---------正在通过redis来查询shopType-list---------");
            //3、存在，转化为list返回
            List<ShopType> list = JSONUtil.toList(shoplist, ShopType.class);
            return Result.ok(list);
        }
        //4、不存在，查询数据库
        log.debug("----------正在通过数据库查询shoptype-list---------");
        List<ShopType> list = shopTypeService.query().orderByAsc("sort").list();
        //5、数据库不存在，返回空列表
        if(list== null){
            return Result.ok(list);
        }
        //6、数据库存在，写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_LIST_KEY,JSONUtil.toJsonStr(list));
        //7、返回
        return Result.ok(list);

    }
}
